package com.demo.function;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.demo.MainActivity;
import com.demo.androidfunctiondemo.R;

import java.io.FileInputStream;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DownloadManagerActivity extends AppCompatActivity {

    @BindView(R.id.imageview)
    ImageView imageview;

    private static final String DL_ID = "downloadId";
    private SharedPreferences prefs;
    private DownloadManager dm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_manager);
        ButterKnife.bind(this);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!prefs.contains(DL_ID)) {
            Uri resource = Uri.parse("http://www.bigfoto.com/dog-animal.jpg");
            DownloadManager.Request request = new DownloadManager.Request(resource);
            request.setAllowedOverRoaming(false);
            //设置WIFI下进行更新
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI|DownloadManager.Request.NETWORK_MOBILE);
            //下载中和下载完后都显示通知栏
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            //使用系统默认的下载路径 此处为应用内 /android/data/packages ,所以兼容7.0
            request.setDestinationInExternalFilesDir(DownloadManagerActivity.this, Environment.DIRECTORY_DOWNLOADS, "下载");
            //通知栏标题
            request.setTitle("下载");
            //通知栏描述信息
            request.setDescription("下载测试");
            //设置类型为.apk
            request.setMimeType("application/vnd.android.package-archive");
            Long id = dm.enqueue(request);
            prefs.edit().putLong(DL_ID, id).commit();
        }else {
            // 下载已经开始，检查下载状态
            queryDownloadStatus();
        }

        registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            queryDownloadStatus();
        }
    };


    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Cursor c = dm.query(query);
        if (c.moveToFirst()) {

            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {

                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:

                    try {
                        ParcelFileDescriptor file = dm.openDownloadedFile(prefs.getLong(DL_ID, 0));
                        FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(file);
                        imageview.setImageBitmap(BitmapFactory.decodeStream(fis));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                case DownloadManager.STATUS_FAILED:
                    // 清除下载并稍后重试
                    dm.remove(prefs.getLong(DL_ID,0));
                    prefs.edit().clear().commit();
                    break;

            }

        }

    }

}
